<template>
  <div class="main">
    <mine-title>新建数据集</mine-title>
    <div class="content" v-loading="loading">
      <div class="form-limit">
        <el-form ref="form" :model="form" label-width="110px" :rules="rules">
          <el-form-item label="数据集类型：" prop="fileType">
            <el-radio-group
              v-model="form.fileType"
              @change="handleFileTypeChange"
            >
              <el-radio
                v-for="(item, i) in classifies"
                :key="i"
                :label="item.name"
                >{{ item.text }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数据集名称：" prop="fileName">
            <el-input v-model="form.fileName" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item label="数据集描述：" prop="fileDesc">
            <el-input type="textarea" v-model="form.fileDesc"></el-input>
          </el-form-item>
          <!-- <el-form-item v-if="isTxt">
            <el-radio-group v-model="uploadType" size="small">
              <el-radio-button label="file">数据文件</el-radio-button>
              <el-radio-button label="sql">连接数据库</el-radio-button>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item
            :required="true"
            label="上传文件："
            prop="file"
            key="file"
            v-if="uploadType === 'file'"
          >
            <mine-upload
              ref="upload"
              :fileType="accept"
              @change="onChange"
            ></mine-upload>
            <div class="text-left margin-bottom-10">
              <mine-button
                secondary
                size="mini"
                @click="downloadFile"
                :disabled="!form.fileType"
                :loading="downloading"
                >下载模板<i class="iconfont icon-download-line is-right"></i
              ></mine-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-form :model="form" label-width="110px" :rules="rules">
          <el-form-item
            label=""
            prop="sql"
            key="sql"
            v-if="uploadType === 'sql'"
          >
            <linkView ref="linkView"></linkView>
          </el-form-item>
          <el-form-item class="form-btn-row">
            <mine-button type="primary" @click="onCancel" secondary
              >取 消</mine-button
            >
            <mine-button type="primary" @click="onSubmit">保 存</mine-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/modules/index/utils/request";
import { downloadFile, classifyList } from "@/utils/common";
import _ from "lodash";
import linkView from "./components/linkView";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
export default {
  name: "dataAdminEdit",
  components: {
    linkView,
  },
  data() {
    return {
      form: {
        fileName: "",
        fileType: "",
        fileDesc: "",
        file: "",
      },
      rules: {
        fileName: [
          {
            required: true,
            message: "请输入数据集名称",
            trigger: "blur",
          },
        ],
        fileType: [
          {
            required: true,
            message: "请输入数据集类型",
            trigger: "blur",
          },
        ],
        fileDesc: [
          {
            required: true,
            message: "请输入数据集描述",
            trigger: "blur",
          },
        ],

        file: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      fileList: [],
      loading: false,
      uploadType: "file", // [file, sql]
      downloading: false,
    };
  },
  methods: {
    onSubmit() {
      let _this = this;
      this.$refs.form.validate(async (valid, object) => {
        let { form, fileName, fileType, fileDesc } = _this;
        if (form.id) {
          var obj = {
              fileName: form.fileName,
              fileType: form.fileType,
              fileDesc: form.fileDesc,
              projectId: "",
            },
            obj2 = { fileName, fileType, fileDesc };
          if (_.isEqual(obj, obj2)) {
            _this.onSubmitFile(form.id);
          }
          return false;
        }
        if (valid) {
          if (this.uploadType === "file") {
            if (valid) {
              this.loading = true;

              let res = {};
              let _self = this;
              if (_self.$qwebUtil.isQtClient) {
                const uuid = _self.$qwebUtil.generateRandomUUID();
                let sendObject;
                /* eslint-disable-next-line */
                const channel = new QWebChannel(
                  window.qt.webChannelTransport,
                  async function (channel) {
                    sendObject = channel.objects.sendObject;
                    // receivedJSON 修改此处发送请求参数
                    const receivedJSON = {
                      RequestUrl: "/material-info/save-no-project",
                      RequestMethod: "post",
                      ContentType: "application/json;charset=UTF-8",
                      RequestBody: form,
                      isStringParam: false,
                      requestId: uuid,
                    };
                    await send();
                    await _self.$qwebUtil.receive(sendObject, receivedJSON);
                    // console.error('received','/feCanvas/pageList')
                  }
                );
                /* eslint-disable-next-line */
                async function send() {
                  sendObject.sendMessage.connect(function (data) {
                    this.loading = false;
                    if (!data) {
                      console.error("No data received.");
                    }
                    res = JSON.parse(data);
                    const result = res.response || {};
                    // update the followings
                    if (result.success && res.webInfo.requestId == uuid) {
                      _self.fileName = form.fileName;
                      _self.fileType = form.fileType;
                      _self.fileDesc = form.fileDesc;
                      _self.onSubmitFile(result.data.id);
                    } else {
                      _self.$message.warning(result.msg);
                    }
                  });
                }
              } else if (this.$webview2.isWPF) {
                const uuid = this.$webview2.generateRandomUUID();
                await this.$webview2.sendWebView2(
                  "/material-info/save-no-project",
                  "post",
                  "application/json;charset=UTF-8",
                  form,
                  false,
                  uuid
                );
                await window.chrome.webview.addEventListener(
                  "message",
                  (e) => {
                    let res = e.data.response;
                    // TODO： 定制后台数据处理
                    if (res.status === 200) {
                      let result = res;
                      this.loading = false;
                      if (!result.success) {
                        return;
                      }
                      this.fileName = form.fileName;
                      this.fileType = form.fileType;
                      this.fileDesc = form.fileDesc;
                      _this.onSubmitFile(result.data.id);
                    } else {
                      this.loading = false;
                      this.$message.warning(res.msg);
                    }
                  },
                  { once: true }
                );
              } else {
                request({
                  url: "/material-info/save-no-project", //接口
                  method: "post",
                  data: form,
                })
                  .then((response) => {
                    let result = response.data;
                    if (!result.success) {
                      this.loading = false;
                      return;
                    }
                    this.fileName = form.fileName;
                    this.fileType = form.fileType;
                    this.fileDesc = form.fileDesc;
                    _this.onSubmitFile(result.data.id);
                  })
                  .catch(() => {
                    this.loading = false;
                  });
              }
            } else {
              return false;
            }
          } else {
            const link = await this.$refs.linkView.getResult();
            if (!link) return;
            const sql = link.sql || "";
            const connId = link.id || "";
            if (valid) {
              const params = {
                fileName: form.fileName,
                fileType: form.fileType,
                fileDesc: form.fileDesc,
                sqlFile: "sql",
                sqlSyntax: sql,
                connId: connId,
              };
              this.loading = true;
              let res = {};
              let _self = this;
              if (_self.$qwebUtil.isQtClient) {
                const uuid = _self.$qwebUtil.generateRandomUUID();
                let sendObject;
                /* eslint-disable-next-line */
                const channel = new QWebChannel(
                  window.qt.webChannelTransport,
                  async function (channel) {
                    sendObject = channel.objects.sendObject;
                    // receivedJSON 修改此处发送请求参数
                    const receivedJSON = {
                      RequestUrl: "/material-info/save-no-project",
                      RequestMethod: "post",
                      ContentType: "application/json;charset=UTF-8",
                      RequestBody: params,
                      isStringParam: false,
                      requestId: uuid,
                    };
                    await send();
                    await _self.$qwebUtil.receive(sendObject, receivedJSON);
                    // console.error('received','/feCanvas/pageList')
                  }
                );
                /* eslint-disable-next-line */
                async function send() {
                  sendObject.sendMessage.connect(function (data) {
                    this.loading = false;
                    if (!data) {
                      console.error("No data received.");
                    }
                    res = JSON.parse(data);
                    const result = res.response || {};
                    // update the followings
                    if (result.success && res.webInfo.requestId == uuid) {
                      _self.$router.push("/datalist");
                    }
                  });
                }
              } else {
                request({
                  url: "/material-info/save-no-project", //接口
                  method: "post",
                  data: params,
                }).then((response) => {
                  let result = response.data;
                  if (!result.success) {
                    this.loading = false;
                    return;
                  } else {
                    this.loading = false;
                    this.$confirm(
                      "数据集保存成功，是否需要返回列表？",
                      "提示",
                      {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                      }
                    )
                      .then(() => {
                        this.$router.push("/datalist");
                      })
                      .catch(() => {});
                  }
                });
              }
            }
          }
        }
      });
    },
    handleFileTypeChange() {
      const fileType = this.form.fileType;
      // 图像分类，单类别、声音分类、图像检测
      if (
        ["img_classify", "voice_classify", "img_detection"].includes(fileType)
      ) {
        this.uploadType = "file";
      }
    },
    onSubmitFile(id) {
      this.form.id = id;
      let formData = new FormData();
      formData.append("File", this.fileList[0].raw);
      formData.append("id ", id);
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(this.fileList[0].raw);
        reader.onload = async (e) => {
          formData = e.target.result;
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/material-info/upload-no-project/${id}`,
                RequestMethod: "post",
                ContentType: "multipart/form-data",
                RequestBody: {
                  File: formData,
                  fileName: _self.fileList[0].name,
                },
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.$message.success("上传成功！");
                _self
                  .$confirm("数据集保存成功，是否需要返回列表？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  })
                  .then(() => {
                    _self.$router.push("/datalist");
                  })
                  .catch(() => {});
              } else {
                // _self.$message.warning(result.msg);
              }
            });
          }
        };
      } else if (this.$webview2.isWPF) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(this.fileList[0].raw);
        reader.onload = async (e) => {
          formData = e.target.result;
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/material-info/upload-no-project/${id}`,
            "post",
            "multipart/form-data",
            {
              File: formData,
              fileName: this.fileList[0].name,
            },
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              this.loading = false;
              if (!res.success) {
                this.$message.error("上传失败！");
                return;
              }
              this.$message.success("上传成功！");
              this.$confirm("数据集保存成功，是否需要返回列表？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.$router.push("/datalist");
                })
                .catch(() => {});
            },
            {
              once: true,
              capture: true,
            }
          );
        };
      } else {
        request({
          url: `/material-info/upload-no-project/${id}`, //接口
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
          .then((response) => {
            this.loading = false;
            let result = response.data;
            if (!result.success) {
              this.$message.error("上传失败！");
              return;
            }
            this.$message.success("上传成功！");
            this.$confirm("数据集保存成功，是否需要返回列表？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.$router.push("/datalist");
              })
              .catch(() => {});
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },

    onCancel() {
      this.form = { name: "", type: "", desc: "", version: "", file: "" };
      this.$router.push("/datalist");
    },
    beforeUpload(file) {
      const type = file.type;
      if (!this.accept.includes(type)) {
        this.$message({
          type: "warning",
          message: `请上传${this.accept}类型文件`,
        });
      }
      return true;
    },
    onChange(data) {
      this.form.file = data.file;
      this.fileList = [data.file];
    },
    async downloadFile() {
      this.downloading = true;
      let fileType = this.form.fileType;

      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/material-info/getUrl`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {
                projectType: fileType,
              },
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            //   if (!data) {
            //     console.error("No data received.");
            //   }
            //   res = JSON.parse(data);
            //   const result = res.response || {};
            //   // update the followings
            //   if (result.success && res.webInfo.requestId == uuid) {
            //     // _self.$message.success("删除成功");
            //     // // await this.loadData(true);
            //     // _self.loadOptionData(
            //     //   true,
            //     //   false,
            //     //   _self.$store.state.dictAdmin.currentDirId
            //     // );
            //   } else {
            //     // _self.$message.error(result.msg || "删除失败");
            //   }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/material-info/getUrl`,
          "post",
          "application/json;charset=UTF-8",
          {
            projectType: fileType,
          },
          false,
          uuid
        );
      } else {
        await this.$store.dispatch("dataAdminMaterialInfoGetUrl", {
          projectType: fileType,
        });
      }
      this.downloading = false;
    },
  },
  computed: {
    accept() {
      if (this.form.fileType === "") {
        return ".txt,.csv,.xls,.xlsx,.zip";
      } else if (
        ["data_predict", "txt_classify", "data_unsupervised"].includes(
          this.form.fileType
        )
      ) {
        return ".txt,.csv,.xls,.xlsx";
      } else if (
        ["img_classify", "voice_classify", "img_detection"].includes(
          this.form.fileType
        )
      ) {
        return ".zip";
      }
      return ".txt,.csv,.xls,.xlsx,.zip";
    },
    classifies: function () {
      return [
        {
          name: "data_predict",
          text: "数据预测",
        },
        {
          name: "data_unsupervised",
          text: "无监督学习",
        },
      ];
    },
    isTxt() {
      return ["data_predict", "txt_classify", "data_unsupervised"].includes(
        this.form.fileType
      );
    },
  },
  created() {
    this.$store.commit("SET_BREADCRUMB", [
      { title: "数据集管理", path: "/datalist" },
      { title: "新建建模数据", path: "" },
    ]);
  },
};
</script>
